package com.qf.controller;


import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsCategory;
import com.qf.pojo.DtsGoodsProduct;
import com.qf.service.*;
import com.qf.util.ResponseUtil;
import com.qf.vo.*;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private DtsUserService userService;

    @Autowired
    private DtsGoodsService goodsService;

    @Autowired
    private DtsProductService productService;

    @Autowired
    private DtsOrderService orderService;
    @Autowired
    private DtsCategoryService dtsCategoryService;
    @Autowired
    private DtsAdminService dtsAdminService;
    @Autowired
    private DtsRoleService dtsRoleService;

    //定个查询周期 30天
    private static final int STATIS_DAYS_RANG = 30;// 统计的天数范围，一个月数据
    /**
     * 首页仪表盘
     * 返回用户数, 商品数, 货品库存数, 订单数
     * @return
     */
    @GetMapping("/dashboard")
    public Object info() {

        int userTotal = userService.userCount();
        int goodsTotal = goodsService.count();
        int productTotal = productService.count();
        int orderTotal = orderService.count();
        Map<String, Integer> data = new HashMap<>();
        data.put("userTotal", userTotal);
        data.put("goodsTotal", goodsTotal);
        data.put("productTotal", productTotal);
        data.put("orderTotal", orderTotal);

        return ResponseUtil.ok(data);
    }


    @GetMapping("/dashboard/chart")
    public Object chart(){

        List<CategorySellAmts> categorySellAmtsList =  dtsCategoryService.categorySell();
        //1:categorySell
        CategorySellVo categorySellVo = new CategorySellVo();
        categorySellVo.setCategorySellData(categorySellAmtsList);
        //一级大类目录名称
        String[] categoryNames =
                categorySellAmtsList.stream()
                        .map(CategorySellAmts::getName)
                        .collect(Collectors.toList())
                        .toArray(new String[categorySellAmtsList.size()]);
        categorySellVo.setCategoryNames(categoryNames);


/*        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-30);
        Date time = calendar.getTime();//过去30*/


        //2:orderAmts : 日期和对应的订单总额, 订单笔数
        List<DayStatis> orderDayStatisList = orderService
                .findOrderDayStatis(STATIS_DAYS_RANG);
        OrderAmtsVo orderAmtsVo = fetchOrderAmtsVo(orderDayStatisList);
        //3:userOrderCnt : 日期对应的用户数和订单数
        List<DayStatis> userDayStatisList = userService.findUserDayStatis(STATIS_DAYS_RANG);
        //日期的合并
        List<String> dayDataList = findDayData(orderDayStatisList,userDayStatisList);
        UserOrderCntVo userOrderCntVo = new UserOrderCntVo();
        userOrderCntVo.setDayData(dayDataList);
        List<Integer> userCnt =  fetchOrderAndUserCnt(userDayStatisList,dayDataList);
        List<Integer> orderCnt =  fetchOrderAndUserCnt(orderDayStatisList,dayDataList);
        userOrderCntVo.setUserCnt(userCnt);
        userOrderCntVo.setOrderCnt(orderCnt);
        //结果返回
        Map<String,Object> result = new HashMap<>();
        result.put("categorySell",categorySellVo);
        result.put("orderAmts",orderAmtsVo);
        result.put("userOrderCnt",userOrderCntVo);
        return ResponseUtil.ok(result);
    }

    //获取日期对应的 订单数 或用户数
    private List<Integer> fetchOrderAndUserCnt(List<DayStatis> dayStatisList, List<String> dayDataList) {
        List<Integer> list = new ArrayList<>();
        for (String dayData : dayDataList) {
            // 12-10
            boolean flag = false;
            for (DayStatis dayStatis : dayStatisList) {
                if(dayData.equals(dayStatis.getDayStr())){
                    //产生了订单数或用户数
                    list.add(dayStatis.getCnts());
                    flag = true;
                    break;
                }
            }
            //上面的If语句没进去 证明当前没有产生订单数或用户数
            if(!flag){
                list.add(0);
            }

        }
           /*     "userOrderCnt":{
            "dayData":[
            "2119-12-01","2119-12-02","2119-12-03","2119-12-04",
                    "2119-12-05","2119-12-06","2119-12-07","2119-12-08",
                    "2119-12-09","2119-12-10","2119-12-11","2119-12-12",
                    "2119-12-13","2119-12-14","2119-12-15","2119-12-16",
                    "2119-12-17","2119-12-18","2119-12-19","2119-12-20",
                    "2119-12-21","2119-12-22","2119-12-23","2119-12-24",
                    "2119-12-25","2119-12-26","2119-12-27","2119-12-28",
                    "2119-12-29","2119-12-30"
            ],
            "userCnt":[
            5,9,13,7,6,2,1,3,17,6,2,9,8,17,23,8,
                    4,8,8,14,3,2,1,1,2,1,2,7,3,5
            ],
            "orderCnt":[
            1,2,4,1,3,1,2,3,0,0,1,0,1,0,16,3,9,
                    0,2,1,0,0,2,0,2,0,2,2,2,2
            ]
        }*/
        return list;
    }

    //日期合并
    private List<String> findDayData(List<DayStatis> orderDayStatisList, List<DayStatis> userDayStatisList) {
        Set<String> set = new HashSet<>();

        for (DayStatis dayStatis : orderDayStatisList) {
            set.add(dayStatis.getDayStr());
        }
        for (DayStatis dayStatis : userDayStatisList) {
            set.add(dayStatis.getDayStr());
        }
        //排序
        //set.stream().sorted((s1,s2) -> s1.compareTo(s2));//由小到大
        //set.stream().sorted().collect(Collectors.toSet()).toArray(new String[0]);//由小到大
        return set.stream().sorted().collect(Collectors.toList());//由小到大

    }

    //日期对应订单总金额及订单笔数
    private OrderAmtsVo fetchOrderAmtsVo(List<DayStatis> orderDayStatisList) {
        OrderAmtsVo  vo = new OrderAmtsVo();
        ////////////////日期数组////////////////////////////////
        String[] dayData = new String[orderDayStatisList.size()];
        for (int i = 0; i < orderDayStatisList.size(); i++) {
            dayData[i] = orderDayStatisList.get(i).getDayStr();
        }
        vo.setDayData(dayData);
        ////////////////金额数组////////////////////////////////
        BigDecimal[] orderAmtData = orderDayStatisList.stream()
                .map(DayStatis::getAmts)
                .toArray((value) -> {
                    System.out.println("是长度吗？：" + value);
                    return new BigDecimal[value];
                });
        vo.setOrderAmtData(orderAmtData);
        ////////////////订单笔数数组////////////////////////////////
        Integer[] orderCntData = orderDayStatisList.stream()
                .map(DayStatis::getCnts)
                .toArray((value) -> {
                    System.out.println("是长度吗？：" + value);
                    return new Integer[value];
                });
        vo.setOrderCntData(orderCntData);
/*       "orderAmts":{
            "dayData":[
            "2119-12-01","2119-12-02","2119-12-03","2119-12-04",
                    "2119-12-05","2119-12-06","2119-12-07","2119-12-08",
                    "2119-12-11","2119-12-13","2119-12-15","2119-12-16",
                    "2119-12-17","2119-12-19","2119-12-20","2119-12-23",
                    "2119-12-25","2119-12-27","2119-12-28","2119-12-29",
                    "2119-12-30"
            ],
            "orderAmtData":[
            6.88,138.79,277.65,65.64,182.00,61.00,
                    289.01,375.76,29.50,247.50,145.50,
                    31.18,399.44,16.99,150.01,218.65,255.77,
                    126.59,275.25,97.74,14.63
            ],
            "orderCntData":[
            1,2,4,1,3,1,2,3,1,1,16,3,9,2,1,2,2,2,2,2,2
            ]
        },*/
        return vo;

    }


    /**
     * 系统管理-管理员显示
     *  http://localhost:8083/admin/admin/list?page=1&limit=20&sort=add_time&order=desc
     */
    @GetMapping("/admin/list")
    public Object adminList(int page,int limit,String sort,String order,String username){
        List<DtsAdmin> adminList = dtsAdminService.findAdmins(page,limit,sort,order,username);
        int count = dtsAdminService.count();
        Map<String,Object> result =new HashMap<>();
        result.put("total",count);
        result.put("items",adminList);
        return ResponseUtil.ok(result);
    }
    @GetMapping("/role/options")
    public Object option(){

        List<Map<String, Object>> options = dtsRoleService.options();

        return ResponseUtil.ok(options);
    }
    //创建管理员
    @PostMapping("/admin/create")
    public Object create(@RequestBody DtsAdmin admin, HttpServletRequest request){
        String remoteAddr = request.getRemoteAddr();
        dtsAdminService.create(admin,remoteAddr);
        return ResponseUtil.ok();
    }



}
